﻿
Imports System.Data
Imports System.Data.SqlClient


''' <summary>
''' 倉租收費
''' </summary>
''' <remarks>
''' <list type="Author">Huyang</list>
''' <list type="Date">2008/01/12</list>
''' </remarks>
Public Class Frm_ComputerHire

    Implements IDServer.IDServer.IDServer


#Region "variabled"

#Region "System Variabled Define"




    Public ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp

    Private WithEvents MainForm As Frm_MainForm

    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainForm
        End Get
        Set(ByVal value As Frm_MainForm)
            MainForm = value
        End Set
    End Property

#End Region

#Region "user variabled define"

    ''' <summary>
    ''' 窗體是否加載
    ''' </summary>
    ''' <remarks></remarks>
    Private fLoadBool As Boolean = False

    ''' <summary>
    ''' 記錄上一次的送貨日期
    ''' </summary>
    ''' <remarks></remarks>
    Private fOldDate As String = ""

    ''' <summary>
    ''' 是否是選擇事件
    ''' </summary>
    ''' <remarks></remarks>
    Private AfterCheckBool As Boolean = False

    Dim fDateKey As String = ""

#End Region

#End Region

#Region "Methods"

#Region "返回客戶對應的貨名條碼前綴"

    ''' <summary>
    ''' 返回Key值
    ''' </summary>
    ''' <param name="fCustomerId">客戶編號</param>
    ''' <returns>string</returns>
    ''' <remarks></remarks>
    Private Function GetCustomerGoodsKey(ByVal fCustomerId As String)
        Dim key As String = ""

        Dim sql As String = " select ListCode from dbo.BSC_OtherDefineb where ItemNo =(" & System.Environment.NewLine
        sql &= "              select top 1 Id from dbo.BSC_OtherDefineA  where ItemCode='CustomerGoodsCode')" & System.Environment.NewLine
        sql &= "              and ListA='" & fCustomerId & "'" & System.Environment.NewLine

        Dim obj As Object = Exec(sql, E_ExecType.ExecuteScalar)

        If Not obj Is Nothing Then
            key = obj.ToString()
        End If

        Return key

    End Function

#End Region

#Region "初始化"

    Private Sub Initialize()

        fDateKey = Format(CType(ServerDate, Date), "yyyy-MM") & "-01"
        If IsDate(fDateKey) = True Then
            Me.DateTimePicker1.Text = DateAdd(DateInterval.Day, -1, CType(fDateKey, Date))
            Me.dtp_ChargeSDate.Text = DateAdd(DateInterval.Month, -1, CType(fDateKey, Date))
        End If

        ''設置控件不可用
        Dim cs As setControlEnabled = New setControlEnabled(New Control() {Panel3})
        cs.SetControlsEnabled(False)
        FillCombobox()
        InitDetailGrid()

    End Sub

    Private Function Re_CaptionHash(ByVal index) As Hashtable
        Dim Hash As New Hashtable

        Select Case index
            Case 1

                Hash.Add("fHireCode", "收費單號")
                Hash.Add("fCustomerId", "客戶編號")
                Hash.Add("Cnname", "客戶名稱")
                Hash.Add("fStartDate", "開始日期")
                Hash.Add("fEndDate", "結束日期")
                Hash.Add("fPrice", "單價")
                Hash.Add("FTAmount", "費用")
                Hash.Add("FOther", "其它費用")
                Hash.Add("fArrearMoney", "上次欠費")
                Hash.Add("fPayMoney", "應付金頟")
                Hash.Add("FReceipt", "實收金額")
                Hash.Add("FBSI", "尾數")
                Hash.Add("BillStatus", "狀態")
                Hash.Add("fRemark", "備注")
                Hash.Add("BuildDate", "建檔日期")
                Hash.Add("BuildPsn", "建檔人員")
                Hash.Add("LastUpdateDate", "修改日期")
                Hash.Add("LastUpdatePsn", "修改人員")

            Case 2

                Hash.Add("flage", "標識")
                Hash.Add("StoreHouse", "倉庫")
                Hash.Add("TradeType", "入庫/出庫")
                Hash.Add("DeliverDate", "單據日期")
                Hash.Add("Cubage", "積體")
                Hash.Add("fDays", "天數")
                Hash.Add("fPrice", "單價")
                Hash.Add("fTotalMoney", "費用")

        End Select

        Return Hash
    End Function

    Private Sub InitDetailGrid()
        Dim Dtab As DataTable = InitDetailDtab()
        Me.DataGridView2.DataSource = Dtab
        BindDataGridViewCaption(Me.DataGridView2, Me.Re_CaptionHash(2))
        FullFormatDataGridView(Me.DataGridView2, False, False, False)

    End Sub

    Private Function InitDetailDtab() As DataTable

        Dim Dtab As New DataTable
        With Dtab.Columns
            .Add("flage", GetType(Integer))
            .Add("StoreHouse", GetType(String))
            .Add("TradeType", GetType(String))
            .Add("DeliverDate", GetType(String))
            .Add("Cubage", GetType(Double))
            .Add("fDays", GetType(Integer))
            .Add("fPrice", GetType(Double))
            .Add("fTotalMoney", GetType(Double))
        End With

        Dtab.AcceptChanges()

        Return Dtab
    End Function

    Private Sub FillCombobox()

        Dim sql As String = "select ListCode,ListA from dbo.BSC_OtherDefineB where ItemNo=(select top 1 Id from dbo.BSC_OtherDefineA where ItemCode='BillstatusDefine')"

        Dim dtab As New DataTable
        dtab = Exec(sql, E_ExecType.DataTable)
        Me.ComboBox1.DataSource = dtab
        Me.ComboBox1.ValueMember = "ListCode"
        Me.ComboBox1.DisplayMember = "ListA"

        Me.ComboBox1.Text = ""


    End Sub

#End Region

#Region "查詢"

    Private Sub ExecFind()

        Me.Cursor = Cursors.WaitCursor

        Dim sql As New System.Text.StringBuilder

        Dim whereExp As String = GetWhereSql()


        sql.Append("select fHireCode,fCustomerId,Cnname,fStartDate,fEndDate,fDateKey," & System.Environment.NewLine)
        sql.Append("       fPrice,FTAmount,FOther,fArrearMoney,fPayMoney=FTAmount+FOther+fArrearMoney,FReceipt,FBSI,FPayInFull,BillStatus=ListA,a.fRemark," & System.Environment.NewLine)
        sql.Append("       a.BuildDate,a.BuildPsn,a.LastUpdateDate,a.LastUpdatePsn,a.BuildComputer,a.LastUpdateComputer,a.fReprotDate" & System.Environment.NewLine)
        sql.Append("       from HireCharge a " & System.Environment.NewLine)
        sql.Append("       left join  BSC_Customer b on a.fCustomerId=b.Code" & System.Environment.NewLine)
        sql.Append("       left join (select  ListCode,ListA from dbo.V_BSC_OtherDefine where ItemCode='BillstatusDefine') c on a.BillStatus=c.ListCode")
        sql.Append(whereExp)

        Dim Dtab As New DataTable

        Try

            Dtab = Exec(sql.ToString(), E_ExecType.DataTable)
            Me.DataGridView1.DataSource = Dtab

            BindDataGridViewCaption(Me.DataGridView1, Me.Re_CaptionHash(1))
            FullFormatDataGridView(Me.DataGridView1, False, False, False)
            If Me.fLoadBool = True Then
                SetButton(ButtonType.Browse, True)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            Me.Cursor = Cursors.Default
        End Try

    End Sub

    ''' <summary>
    ''' 返回查詢條件
    ''' </summary>
    ''' <returns>string</returns>
    ''' <remarks></remarks>
    Private Function GetWhereSql()
        Dim sql As String = ""

        If Me.fLoadBool = False Then
            sql &= "  where 1<>1 "
        Else

            sql &= " where 1=1"

            If text_fHireCode.Text.Trim <> "" Then
                sql &= "  and fHireCode='" & Replace_Text(Me.text_fHireCode.Text.Trim) & "'"
            End If

            If text_fCustomerId.Text.Trim <> "" Then
                sql &= " and fCustomerId like '%" & Replace_Text(text_fCustomerId.Text.Trim) & "%'"
            End If

            If text_fCustomerName.Text.Trim <> "" Then
                sql &= " and b.Cnname like '%" & text_fCustomerName.Text.Trim & "%'"
            End If

            sql &= "  and a.fEndDate>='" & dtp_ChargeSDate.Text.Trim & "'"

            sql &= "  and a.fEndDate<='" & DateTimePicker1.Text.Trim & "'"

            If ComboBox1.Text.Trim <> "" AndAlso Not Me.ComboBox1.SelectedValue Is Nothing Then
                sql &= "  and a.BillStatus='" & Me.ComboBox1.SelectedValue & "'"
            End If

        End If

        Return sql
    End Function

#End Region

#Region "Control or ToolBar Set Enabled"

    ''' <summary>
    ''' 設置按鈕狀態
    ''' </summary>
    ''' <param name="type">操作類型</param>
    ''' <param name="IsFind">是否是流覽</param>
    ''' <remarks></remarks>
    Private Sub SetButton(ByVal type As ButtonType, ByVal IsFind As Boolean)
        Try

            Dim BillStatus As String = ""

            If Not Me.DataGridView1.CurrentRow Is Nothing Then
                BillStatus = Me.DataGridView1.CurrentRow.Cells("BillStatus").Value
            End If

            Select Case type
                Case ButtonType.Add
                    With MainForm
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = False
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

                Case ButtonType.Browse
                    With MainForm
                        .ToolStripAdd.Enabled = True
                        .ToolStripEdit.Enabled = IsFind AndAlso (BillStatus = E_VouStatus.保存.ToString OrElse BillStatus = E_VouStatus.反核准.ToString)
                        .ToolStripDelete.Enabled = IsFind AndAlso (BillStatus = E_VouStatus.保存.ToString OrElse BillStatus = E_VouStatus.反核准.ToString)
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = IsFind
                        .ToolStripLast.Enabled = IsFind
                        .ToolStripNext.Enabled = IsFind
                        .ToolStripPrivous.Enabled = IsFind
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True
                        .ToolStripCheck.Enabled = (BillStatus = E_VouStatus.保存.ToString OrElse BillStatus = E_VouStatus.反核准.ToString)
                        .ToolStripComplete.Enabled = False
                        .ToolStripUnCheck.Enabled = (BillStatus = E_VouStatus.核准.ToString)
                    End With

                Case ButtonType.Cancel
                    With MainForm
                        .ToolStripAdd.Enabled = True
                        .ToolStripEdit.Enabled = IsFind
                        .ToolStripDelete.Enabled = IsFind
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = IsFind
                        .ToolStripLast.Enabled = IsFind
                        .ToolStripNext.Enabled = IsFind
                        .ToolStripPrivous.Enabled = IsFind
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

                Case ButtonType.Edit
                    With MainForm
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = False
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

            End Select
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub SetEnabled()
        Me.textfHireCode.ReadOnly = True
        textfCustomerId.ReadOnly = True
        Me.textFTAmount.ReadOnly = True
        Me.textfArrearMoney.ReadOnly = True
        textfPayMoney.ReadOnly = True
        textFBSI.ReadOnly = True
    End Sub

#End Region

#Region "返回值"

    Private Function Re_LastChargeInfo(ByVal fCustomerId As String) As DataTable
        Dim dtab As New DataTable

        Dim sql As String = " select Top 1 *  from HireCharge where fCustomerId='" & fCustomerId & "'  order by fEndDate desc "

        dtab = Exec(sql, E_ExecType.DataTable)

        Return dtab
    End Function

#End Region

#Region "設置Label值"

    Private Sub SetLableVlaue()
        Me.lbBillStatus.Text = E_VouStatus.保存.ToString
        Me.lbUpdateDate.Text = ServerDate
        Me.lbUpdatePsn.Text = PubUserName
    End Sub

#End Region

#Region "FillDetail"

    Private Sub FillDetailText(ByVal fHireCode As String)

        Dim Dtab As DataTable = DirectCast(Me.DataGridView1.DataSource, DataTable)

        Dim Drow() As DataRow = Dtab.Select("fHireCode='" & fHireCode & "'")

        If Drow.Length > 0 Then
            textfHireCode.Text = Drow(0)("fHireCode") & ""
            textfCustomerId.Text = Drow(0)("fCustomerId") & ""
            Me.textfCustomerName.Text = Drow(0)("Cnname") & ""
            ''txtfPrice.Text = Drow(0)("fPrice") & ""
            textFTAmount.Text = Drow(0)("FTAmount") & ""
            textFOther.Text = Drow(0)("FOther") & ""
            textfArrearMoney.Text = Drow(0)("fArrearMoney") & ""
            textfPayMoney.Text = Drow(0)("fPayMoney") & ""
            textFReceipt.Text = Drow(0)("FReceipt") & ""
            textFBSI.Text = Drow(0)("FBSI") & ""
            textfRemark.Text = Drow(0)("fRemark") & ""
            Me.lbBillStatus.Text = Drow(0)("BillStatus") & ""
            Me.lbUpdateDate.Text = IIf(Drow(0)("LastUpdateDate").ToString.Trim <> "", Drow(0)("LastUpdateDate"), Drow(0)("BuildDate"))
            Me.lbUpdatePsn.Text = IIf(Drow(0)("LastUpdatePsn").ToString.Trim <> "", Drow(0)("LastUpdatePsn"), Drow(0)("BuildPsn"))

            If IsDate(Drow(0)("fStartDate")) = True Then
                Me.dtpStartDate.Text = Drow(0)("fStartDate")
            End If
            If IsDate(Drow(0)("fEndDate")) = True Then
                Me.dtpEndDate.Text = Drow(0)("fEndDate")
            End If
            Me.btnComputer.Text = "重新計算"
        Else
            textfHireCode.Text = ""
            textfCustomerId.Text = ""
            Me.textfCustomerName.Text = ""
            ''txtfPrice.Text = ""
            textFTAmount.Text = ""
            textFOther.Text = ""
            textfArrearMoney.Text = ""
            textfPayMoney.Text = ""
            textFReceipt.Text = ""
            textFBSI.Text = ""
            textfRemark.Text = ""
            Me.lbBillStatus.Text = ""
            Me.lbUpdateDate.Text = ""
            Me.lbUpdatePsn.Text = ""
            Me.btnComputer.Text = "計算費用"
        End If
        lbTotalMoney.Text = textfPayMoney.Text
        FillDetailGrid(fHireCode)

    End Sub


    Private Sub FillDetailGrid(ByVal fHireCode As String)

        Dim sql As String = " select flage,StoreHouse,TradeType,DeliverDate,Cubage,fDays,fPrice,fTotalMoney from HireChargeDetail where fHireCode='" & fHireCode & "'"

        Dim Dtab As New DataTable
        Dtab = Exec(sql, E_ExecType.DataTable)

        Me.DataGridView2.DataSource = Dtab
        BindDataGridViewCaption(Me.DataGridView2, Me.Re_CaptionHash(2))
        FullFormatDataGridView(Me.DataGridView2, False, False, False)
        DataGridViewSortModeEnabled(Me.DataGridView2)
    End Sub



#End Region

#End Region

#Region "Events"

#Region "From_Load"

    Private Sub Frm_ComputerHire_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.fLoadBool = False
        Me.Initialize()
        ExecFind()
        Me.fLoadBool = True
    End Sub

#End Region

#Region "Selected fCustomer"

    Private Sub textfCustomerId_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles textfCustomerId.DoubleClick
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
            Dim frm As New Frm_SelectCustomer
            frm.IsFind = True
            If frm.ShowDialog() = DialogResult.OK Then
                Me.textfCustomerId.Text = frm.FCode
                Me.textfCustomerName.Text = frm.FCnname

                Dim Dtab As New DataTable
                Dtab = Re_LastChargeInfo(Me.textfCustomerId.Text.Trim)
                If Dtab.Rows.Count > 0 Then
                    Dim fEndDate As String = Dtab.Rows(0)("fEndDate") & ""
                    Dim FBSI As Double = Val(Dtab.Rows(0)("FBSI") & "")

                    If IsDate(fEndDate) = True Then
                        Dim fDateKey As Date = Format(DateAdd(DateInterval.Month, 1, CType(fEndDate, Date)), "yyyy-MM") & "-01"
                        Me.dtpEndDate.Text = DateAdd(DateInterval.Day, -1, DateAdd(DateInterval.Month, 1, fDateKey))
                        Me.dtpStartDate.Text = fDateKey
                        dtpStartDate.Enabled = False
                    End If
                    Me.textfArrearMoney.Text = FBSI
                Else
                    dtpStartDate.Enabled = True
                    Me.textfArrearMoney.Text = ""
                End If
            End If
        End If
    End Sub

#End Region

#Region "Button"

    Private Sub btnComputer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnComputer.Click
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd OrElse ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then

            Dim fCustomerId As String = Me.textfCustomerId.Text.Trim

            If fCustomerId = "" Then
                MessageBox.Show("客戶編號不能為空，請錄入客戶。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Exit Sub
            End If

            Dim Key As String = GetCustomerGoodsKey(fCustomerId)

            If Key.Trim = "" Then
                MessageBox.Show("客戶貨品編碼規則沒有定義，請先定義。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Exit Sub
            End If

            Dim hirecharge As ComputerHireB = New ComputerHireB()

            hirecharge.StartDate = Me.dtpStartDate.Text
            hirecharge.EndDate = Me.dtpEndDate.Text
            hirecharge.Key = Key
            Dim ic As IhrieComputer = DirectCast(hirecharge, IhrieComputer)
            Dim Dtab As New DataTable
            Dtab = ic.GetHireChargeDataTable()

            Me.DataGridView2.DataSource = Dtab
            BindDataGridViewCaption(Me.DataGridView2, Me.Re_CaptionHash(2))
            FullFormatDataGridView(Me.DataGridView2, False, False, False)
            ''DataGridViewSortModeEnabled(Me.DataGridView2)
            Dim fTotal As Double = Val(Dtab.Compute("sum(fTotalMoney)", "") & "")
            Me.textFTAmount.Text = fTotal
            textfPayMoney.Text = fTotal + Val(textFOther.Text.Trim) + Val(textfArrearMoney.Text.Trim)
            lbTotalMoney.Text = textfPayMoney.Text
            Me.textFBSI.Text = Val(textfPayMoney.Text) - Val(Me.textFReceipt.Text.Trim)
            DataGridView2.Refresh()
            Me.btnComputer.Text = "重新計算"
        End If
    End Sub

    Private Sub btnFind_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFind.Click
        ExecFind()
    End Sub

#End Region

#Region "Text Changed"

    Private Sub textFReceipt_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles textFReceipt.TextChanged

        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd OrElse ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
            Dim fPayMoney As Double = Val(Me.textfPayMoney.Text.Trim)
            Me.textFBSI.Text = fPayMoney - Val(Me.textFReceipt.Text.Trim)
        End If

    End Sub

    Private Sub textFOther_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles textFOther.TextChanged
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd OrElse ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
            Dim FTAmount As Double = Val(Me.textFTAmount.Text.Trim)
            Me.textfPayMoney.Text = FTAmount + Val(Me.textFOther.Text.Trim) + Val(textfArrearMoney.Text.Trim)
        End If
    End Sub

    Private Sub textfPayMoney_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles textfPayMoney.TextChanged
        lbTotalMoney.Text = textfPayMoney.Text
    End Sub

#End Region

#Region "DataGrid"

    Private Sub DataGridView1_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellDoubleClick
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then
            Me.TabControl1.SelectedIndex = 1
        End If
    End Sub

    Private Sub DataGridView1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.SelectionChanged
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then
            SetButton(ButtonType.Browse, True)
        End If
    End Sub



#End Region

#Region "TabControl"

    Private Sub TabControl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
        If Me.TabControl1.SelectedIndex = 1 Then
            Dim fHireCode As String = ""
            If Not Me.DataGridView1.CurrentRow Is Nothing Then
                fHireCode = Me.DataGridView1.CurrentRow.Cells("fHireCode").Value
            End If
            FillDetailText(fHireCode)
        End If
    End Sub

    Private Sub TabControl1_Selecting(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlCancelEventArgs) Handles TabControl1.Selecting
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd OrElse ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
            e.Cancel = True
        End If
    End Sub

#End Region

#End Region

#Region "數據處理"


    ''' <summary>
    ''' 保存過程
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function btnSaveData() As Boolean

        Dim fHireCode As String = ""
        Dim ShopNo As String = PubCompanyCode
        Dim fCustomerId As String = Me.textfCustomerId.Text.Trim
        Dim fCustomerName As String = Me.textfCustomerName.Text.Trim
        Dim fStartDate As String = Me.dtpStartDate.Text.Trim
        Dim fEndDate As String = Me.dtpEndDate.Text.Trim
        Dim fPrice As Double = 0
        Dim FTAmount As Double = Val(Me.textFTAmount.Text.Trim)
        Dim FOther As Double = Val(Me.textFOther.Text.Trim)
        Dim fArrearMoney As Double = Val(Me.textfArrearMoney.Text.Trim)
        Dim FReceipt As Double = Val(Me.textFReceipt.Text.Trim)
        Dim FBSI As Double = Val(Me.textFBSI.Text.Trim)
        Dim FPayInFull As Integer = IIf(FBSI > -1 AndAlso FBSI < 1, 1, 0)
        Dim fRemark As String = Me.textfRemark.Text.Trim

        If ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
            fHireCode = Me.textfHireCode.Text
        Else
            fHireCode = Exec("exec [ReturnBillNum] 'HireCharge','fHireCode','" & ShopNo & "'", E_ExecType.ExecuteScalar)
            Me.textfHireCode.Text = fHireCode

        End If

        Dim SQL As New System.Text.StringBuilder

        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
            SQL.Append("Insert Into [HireCharge](" & System.Environment.NewLine)
            SQL.Append("fHireCode,ShopNo,fCustomerId,fStartDate,fEndDate,fDateKey,BillStatus,fPrice," & System.Environment.NewLine)
            SQL.Append("FTAmount,FOther,fArrearMoney,FReceipt,FBSI,FPayInFull,fRemark,BuildDate,BuildPsn,BuildComputer" & System.Environment.NewLine)
            SQL.Append(")" & System.Environment.NewLine)
            SQL.Append("values(" & System.Environment.NewLine)
            SQL.Append("'" & fHireCode & "','" & ShopNo & "','" & fCustomerId & "','" & fStartDate & "','" & fEndDate & "',Convert(nvarchar(19),Getdate(),21),'A'," & fPrice & "," & System.Environment.NewLine)
            SQL.Append("" & FTAmount & "," & FOther & "," & fArrearMoney & "," & FReceipt & "," & FBSI & "," & FPayInFull & ",'" & fRemark & "',Convert(nvarchar(19),Getdate(),21),'" & PubUserName & "','" & My.Computer.Name & "'" & System.Environment.NewLine)
            SQL.Append(" )")
        Else

            SQL.Append("Update HireCharge set" & System.Environment.NewLine)
            SQL.Append("ShopNo='" & ShopNo & "',")
            SQL.Append("fCustomerId='" & fCustomerId & "',")
            SQL.Append("fStartDate='" & fStartDate & "',")
            SQL.Append("fEndDate='" & fEndDate & "',")
            SQL.Append("fDateKey=Convert(nvarchar(19),getdate(),21),")
            SQL.Append("BillStatus='A',")
            SQL.Append("fPrice=" & fPrice & ",")
            SQL.Append("FTAmount=" & FTAmount & ",")
            SQL.Append("FOther=" & FOther & ",")
            SQL.Append("fArrearMoney=" & fArrearMoney & ",")
            SQL.Append("FReceipt=" & FReceipt & ",")
            SQL.Append("FBSI=" & FBSI & ",")
            SQL.Append("FPayInFull=" & FPayInFull & ",")
            SQL.Append("fRemark='" & fRemark & "',")
            SQL.Append("LastUpdateDate=Convert(nvarchar(19),getdate(),21),")
            SQL.Append("LastUpdatePsn='" & PubUserName & "',")
            SQL.Append("LastUpdateComputer='" & My.Computer.Name & "'")
            SQL.Append("where fHireCode='" & fHireCode & "'" & System.Environment.NewLine)

            ''刪除明細表
            SQL.Append("delete HireChargedetail where fHireCode='" & fHireCode & "'")
        End If

        Dim Dtab As DataTable = DirectCast(Me.DataGridView2.DataSource, DataTable)

        Dim DetailDtab As New DataTable

        DetailDtab = ReturnDetailDataTable(fHireCode, Dtab)

        Dim SqlCN As SqlClient.SqlConnection
        SqlCN = GetConn()
        Dim SqlTran As SqlClient.SqlTransaction
        Dim SqlCmd As New SqlClient.SqlCommand
        Dim SqlBulk As SqlBulkCopy
        SqlTran = SqlCN.BeginTransaction

        Try

            With SqlCmd
                .CommandText = SQL.ToString.Trim
                .CommandType = CommandType.Text
                .Connection = SqlCN
                .Transaction = SqlTran
                .ExecuteNonQuery()
            End With

            SqlBulk = New SqlBulkCopy(SqlCN, SqlBulkCopyOptions.Default, SqlTran)
            SqlBulk.DestinationTableName = "HireChargedetail"
            SqlBulk.BulkCopyTimeout = 100
            SqlBulk.WriteToServer(DetailDtab)

            SqlTran.Commit()

        Catch ex As Exception
            SqlTran.Rollback()
            MessageBox.Show(IIf(ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd, My.Resources.ErrAdd, My.Resources.ErrEdit) & ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)

        Finally
            SqlCN.Close()
            SqlCN.Dispose()
            SqlCmd.Dispose()
            SqlTran.Dispose()
        End Try

        UpdateData(fHireCode, fCustomerId, fCustomerName, fStartDate, fEndDate, fPrice, FTAmount, FOther, fArrearMoney, FReceipt, FBSI, FPayInFull, fRemark)

        Dim cs As New setControlEnabled(New Control() {Me.Panel3})
        cs.SetControlsEnabled(False)
        Me.textfCustomerId.BackColor = Me.textfCustomerName.BackColor
        MessageBox.Show(IIf(ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd, My.resources.Addsuccess, My.resources.EditSuccess), Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
        SetButton(ButtonType.Browse, True)

        Return True
    End Function

    ''' <summary>
    ''' 返回明細數據表
    ''' </summary>
    ''' <param name="fHireCode">單號</param>
    ''' <param name="DetailDtab">明細網格數據源</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ReturnDetailDataTable(ByVal fHireCode As String, ByVal DetailDtab As DataTable)
        Dim Dtab As New DataTable

        With Dtab.Columns
            .Add("fHireCode", GetType(String))
            .Add("flage", GetType(Integer))
            .Add("StoreHouse", GetType(String))
            .Add("TradeType", GetType(String))
            .Add("DeliverDate", GetType(String))
            .Add("Cubage", GetType(Double))
            .Add("fDays", GetType(Integer))
            .Add("fPrice", GetType(Double))
            .Add("fTotalMoney", GetType(Double))
        End With

        For Each Row As DataRow In DetailDtab.Rows
            Dim NewRow As DataRow = Dtab.NewRow
            NewRow("fHireCode") = fHireCode
            NewRow("flage") = Row("flage")
            NewRow("StoreHouse") = Row("StoreHouse")
            NewRow("TradeType") = Row("TradeType")
            NewRow("DeliverDate") = Row("DeliverDate")
            NewRow("Cubage") = Row("Cubage")
            NewRow("fDays") = Row("fDays")
            NewRow("fPrice") = Row("fPrice")
            NewRow("fTotalMoney") = Row("fTotalMoney")

            Dtab.Rows.Add(NewRow)

        Next

        Dtab.AcceptChanges()

        Return Dtab

    End Function

    ''' <summary>
    ''' 更新數據集
    ''' </summary>
    ''' <param name="fHireCode"></param>
    ''' <param name="fCustomerId"></param>
    ''' <param name="fCustomerName"></param>
    ''' <param name="fStartDate"></param>
    ''' <param name="fEndDate"></param>
    ''' <param name="fPrice"></param>
    ''' <param name="FTAmount"></param>
    ''' <param name="FOther"></param>
    ''' <param name="fArrearMoney"></param>
    ''' <param name="FReceipt"></param>
    ''' <param name="FBSI"></param>
    ''' <param name="FPayInFull"></param>
    ''' <param name="fRemark"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function UpdateData(ByVal fHireCode As String, ByVal fCustomerId As String, ByVal fCustomerName As String, ByVal fStartDate As String, _
                                 ByVal fEndDate As String, ByVal fPrice As Double, ByVal FTAmount As Double, ByVal FOther As Double, _
                                 ByVal fArrearMoney As Double, ByVal FReceipt As Double, ByVal FBSI As Double, ByVal FPayInFull As Double, ByVal fRemark As String) As Boolean

        Dim Dtab As New DataTable
        Dtab = DirectCast(Me.DataGridView1.DataSource, DataTable)

        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
            Dim Row As DataRow = Dtab.NewRow
            Row("fHireCode") = fHireCode
            Row("fCustomerId") = fCustomerId
            Row("Cnname") = fCustomerName
            Row("fStartDate") = fStartDate
            Row("fEndDate") = fEndDate
            Row("fPrice") = fPrice
            Row("FTAmount") = FTAmount
            Row("FOther") = FOther
            Row("fArrearMoney") = fArrearMoney
            Row("FReceipt") = FReceipt
            Row("FBSI") = FBSI
            Row("FPayInFull") = FPayInFull
            Row("fRemark") = fRemark
            Row("BuildDate") = ServerDate
            Row("BuildPsn") = PubUserName
            Row("BillStatus") = E_VouStatus.保存.ToString()
            Row("BuildComputer") = My.Computer
            Dtab.Rows.Add(Row)

        Else

            Dim DRow() As DataRow = Dtab.Select("fHireCode='" & fHireCode & "'")

            If DRow.Length > 0 Then
                Dim Row As DataRow = DRow(0)
                Row("fCustomerId") = fCustomerId
                Row("Cnname") = fCustomerName
                Row("fStartDate") = fStartDate
                Row("fEndDate") = fEndDate
                Row("fPrice") = fPrice
                Row("FTAmount") = FTAmount
                Row("FOther") = FOther
                Row("fArrearMoney") = fArrearMoney
                Row("FReceipt") = FReceipt
                Row("FBSI") = FBSI
                Row("FPayInFull") = FPayInFull
                Row("fRemark") = fRemark

                Row("LastUpdateDate") = ServerDate
                Row("LastUpdatePsn") = PubUserName
                Row("BillStatus") = E_VouStatus.保存.ToString()
                Row("LastUpdateComputer") = My.Computer
            End If

        End If
        Dtab.AcceptChanges()
        Return True
    End Function

    ''' <summary>
    ''' 驗證是否可以刪除
    ''' </summary>
    ''' <param name="fHireCode">收費單號</param>
    ''' <returns>Boolean</returns>
    ''' <remarks></remarks>
    Private Function ValidatedDelete(ByVal fHireCode) As Boolean
        Dim Bool As Boolean = True

        Dim Sql As New System.Text.StringBuilder
        Sql.Append("select * from HireCharge where fHireCode='" & fHireCode & "'")

        Dim dtab As New DataTable
        dtab = Exec(Sql.ToString, E_ExecType.DataTable)

        If dtab.Rows.Count <= 0 Then
            MessageBox.Show("記錄已刪除，請重新刷新！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Bool = False
            GoTo A
        End If

        If dtab.Rows(0)("BillStatus").ToString.Trim = "B" OrElse dtab.Rows(0)("BillStatus").ToString.Trim = "F" Then
            MessageBox.Show("記錄已審核，請重新刷新！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Bool = False
            GoTo A
        End If

A:
        Return Bool

    End Function

    Private Function UpdateDateDeleted() As Boolean

        Try
            Dim Index As Integer = Me.DataGridView1.CurrentRow.Index

            Me.DataGridView1.Rows.RemoveAt(Index)

            Me.DataGridView1.Update()

            If Index > 0 Then
                Index -= 1
            End If

            If Me.DataGridView1.Rows.Count > 0 Then
                If Index < Me.DataGridView1.Rows.Count Then
                    Me.DataGridView1.CurrentCell = Me.DataGridView1.Rows(Index).Cells("fHireCode")
                End If
            Else
                Me.DataGridView1.CurrentCell = Me.DataGridView1.Rows(0).Cells("fHireCode")
            End If

            Dim fHireCode As String = ""
            If Not Me.DataGridView1.CurrentRow Is Nothing Then

                fHireCode = Me.DataGridView1.CurrentRow.Cells("fHireCode").Value
                Me.DataGridView1.CurrentRow.Selected = True

            End If
            If Me.TabControl1.SelectedIndex = 1 Then
                Me.FillDetailText(fHireCode)
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
        Return True
    End Function

#End Region

#Region "接口"


    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd
        If AddEnable = False Then
            MessageBox.Show("對不起，您沒有新增權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If

        If Me.TabControl1.SelectedIndex = 0 Then
            Me.TabControl1.SelectedIndex = 1
        End If
        ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd
        Dim cs1 As New setControlEnabled(New Control() {Me.Panel3})
        cs1.SetControlsEnabled(True)
        FillDetailText("")
        SetLableVlaue()
        SetEnabled()
        Me.dtpStartDate.Text = DateAdd(DateInterval.Month, -1, CType(fDateKey, Date))
        Me.dtpEndDate.Text = DateAdd(DateInterval.Day, -1, CType(fDateKey, Date))
        SetButton(ButtonType.Add, False)
        Me.textfCustomerId.BackColor = Me.textfCustomerName.BackColor
        Me.textfCustomerId.Focus()
        Return True
    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel
        ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
        Dim cs1 As New setControlEnabled(New Control() {Me.Panel3})
        cs1.SetControlsEnabled(False)
        SetButton(ButtonType.Browse, True)
        Me.textfCustomerId.BackColor = Me.textfCustomerName.BackColor
        Dim fHireCode As String = ""
        If Not Me.DataGridView1.CurrentRow Is Nothing Then
            fHireCode = Me.DataGridView1.CurrentRow.Cells("fHireCode").Value
        End If
        FillDetailText(fHireCode)

        Return True
    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete
        If DeleteEnable = False Then
            MessageBox.Show("對不起，您沒有刪除權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If

        If Me.DataGridView1.CurrentRow Is Nothing Then Return True

        Dim fHireCode As String = Me.DataGridView1.CurrentRow.Cells("fHireCode").Value

        If ValidatedDelete(fHireCode) = False Then
            Return True
        End If

        Dim SQL As New System.Text.StringBuilder

        SQL.Append("delete HireChargeDetail where fHireCode='" & fHireCode & "'")
        SQL.Append("delete HireCharge where fHireCode='" & fHireCode & "'")

        Try

            Exec(SQL.ToString, E_ExecType.ExecuteNonQuery, True)

        Catch ex As Exception
            MessageBox.Show(My.Resources.ErrDelete, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

        If UpdateDateDeleted() = True Then
            MessageBox.Show(My.Resources.DeleteSuccess, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        Else
            MessageBox.Show(My.Resources.ErrDelete, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If

        ''  Me.SetButton(ButtonType.Browse, True)

        Return True

    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit
        If EditEnable = False Then
            MessageBox.Show("對不起，您沒有修改權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If

        If Me.TabControl1.SelectedIndex = 0 Then
            Me.TabControl1.SelectedIndex = 1
        End If
        ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit
        Dim cs1 As New setControlEnabled(New Control() {Me.Panel3})
        cs1.SetControlsEnabled(True)
        SetLableVlaue()
        SetEnabled()
        SetButton(ButtonType.Add, False)
        Me.textfCustomerName.ReadOnly = True
        Me.dtpEndDate.Focus()
        Return True
    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport

    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter

    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint

    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave
        Dim bool As Boolean = btnSaveData()
        Return bool
    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect

    End Function

    ''' <summary>
    ''' 審核過成
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ActionChecked() As Boolean
        If CheckEnable = False Then
            MessageBox.Show("對不起，您沒有審核權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If

        If Me.DataGridView1.CurrentRow Is Nothing Then Return True

        Dim fHireCode As String = DataGridView1.CurrentRow.Cells("fHireCode").Value

        Dim SQL As New System.Text.StringBuilder

        SQL.Append("Update HireCharge set BillStatus='B' where fHireCode='" & fHireCode & "'")

        Try

            Exec(SQL.ToString, E_ExecType.ExecuteNonQuery)

        Catch ex As Exception
            MessageBox.Show(My.Resources.ErrCheck, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

        Dim Dtab As New DataTable
        Dtab = DirectCast(Me.DataGridView1.DataSource, DataTable)

        Dim DRow() As DataRow = Dtab.Select("fHireCode='" & fHireCode & "'")

        If DRow.Length > 0 Then
            DRow(0).Item("BillStatus") = E_VouStatus.核准.ToString
        End If

        Dtab.AcceptChanges()

        If Me.TabControl1.SelectedIndex = 1 Then
            Me.lbBillStatus.Text = E_VouStatus.核准.ToString
        End If

        MessageBox.Show(My.Resources.CheckSuccess, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)

        Me.SetButton(ButtonType.Browse, True)

        Return True

    End Function

    ''' <summary>
    ''' 反審核
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ActionUnchecked() As Boolean
        If UncheckEnable = False Then
            MessageBox.Show("對不起，您沒有反審核權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If

        If Me.DataGridView1.CurrentRow Is Nothing Then Return True

        Dim fHireCode As String = DataGridView1.CurrentRow.Cells("fHireCode").Value

        Dim SQL As New System.Text.StringBuilder

        SQL.Append("Update HireCharge set BillStatus='C' where fHireCode='" & fHireCode & "'")

        Try

            Exec(SQL.ToString, E_ExecType.ExecuteNonQuery)

        Catch ex As Exception
            MessageBox.Show(My.Resources.ErrUnCheck, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

        Dim Dtab As New DataTable
        Dtab = DirectCast(Me.DataGridView1.DataSource, DataTable)

        Dim DRow() As DataRow = Dtab.Select("fHireCode='" & fHireCode & "'")

        If DRow.Length > 0 Then
            DRow(0).Item("BillStatus") = E_VouStatus.反核准.ToString
        End If

        Dtab.AcceptChanges()

        If Me.TabControl1.SelectedIndex = 1 Then
            Me.lbBillStatus.Text = E_VouStatus.反核准.ToString
        End If

        MessageBox.Show(My.Resources.UnCheckSuccess, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)

        Me.SetButton(ButtonType.Browse, True)

        Return True

    End Function

    ''' <summary>
    ''' 完成
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ActionComplete() As Boolean
     
    End Function

#End Region


    Private Sub Panel1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Panel1.Paint

    End Sub

    Private Sub GroupBox1_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GroupBox1.Enter

    End Sub

    Private Sub GroupBox2_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GroupBox2.Enter

    End Sub
End Class
